AddPrefabPostInit("sunkenchest", function(inst)
    if not TheWorld.ismastersim then
        return
    end

    if inst.components.container ~= nil then
        inst.components.container.canbeopened = true

        -- 只在第一次打开时填充物品
        if inst._filled_loot == nil then
            inst._filled_loot = false
        end

        local function FillLootOnOpen(inst)
            if inst._filled_loot then return end
            inst._filled_loot = true

            if inst.components.lootdropper ~= nil then
                local loot = inst.components.lootdropper:GenerateLoot()
                for _, prefab in ipairs(loot) do
                    local item = SpawnPrefab(prefab)
                    if item ~= nil then
                        if item.components.stackable then
                            item.components.stackable:SetStackSize(1)
                        end
                        inst.components.container:GiveItem(item)
                    end
                end
            end
        end

        -- 添加打开和关闭事件的处理
        inst:ListenForEvent("onopen", function(inst)
            FillLootOnOpen(inst)
            if inst.components.container.EnableReadOnlyContainer then
                inst.components.container:EnableReadOnlyContainer(true)
            end
        end)

        inst:ListenForEvent("onclose", function(inst)
            if inst.components.container.EnableReadOnlyContainer then
                inst.components.container:EnableReadOnlyContainer(false)
            end
        end)
    end
end)
